package com.example.pilipili.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class FileU {

    private static final String FILE_BASE_URL = "E:/pilipili/" ;

    public static String uploadFileToLocal(MultipartFile file, String dir) {
        try {
            String uploadDirPath = FILE_BASE_URL + dir ; // 构建完整的上传目录路径
            File uploadDir = new File(uploadDirPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            String originalFileName = file.getOriginalFilename();
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + extension; // 使用UUID重命名文件
            File uploadFile = new File(uploadDir, newFileName);
            file.transferTo(uploadFile);
            return dir+"/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public static boolean deleteFile(String fileName) {
        try {
            String filePath = FILE_BASE_URL  + fileName; // 构建文件完整路径
            File file = new File(filePath);
            System.out.println(filePath);
            if (file.exists()) {
                if (file.delete()) {
                    System.out.println("文件删除成功");
                    return true;
                } else {
                    System.out.println("文件删除失败");
                    return false;
                }
            } else {
                System.out.println("文件不存在");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

}
